package com.mis.clothespos.shiro.config;

import com.mis.clothespos.shiro.Role.service.RoleService;
import com.mis.clothespos.shiro.common.ShiroUtils;
import com.mis.clothespos.shiro.user.domain.User;
import com.mis.clothespos.shiro.permission.service.permissionService;
import com.mis.clothespos.shiro.user.service.loginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
//    @Resource
//    private UserInfoService userInfoService;

    private static final Logger log = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    RoleService roleService;
    @Autowired
    permissionService p;
    @Autowired
    loginService l;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        //从Security中获取当前的subject的凭证变成user返回来
        String userName = ShiroUtils.getSysUser();
        User user = l.selectUserByUserName(userName);
        // 角色列表
        Set<String> roles = new HashSet<String>();
        // 功能列表
        Set<String> menus = new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        roles = roleService.selectRoleKeys(Long.valueOf(user.getId()));
        menus = p.selectPermsByUserId(Long.valueOf(user.getId()));
        // 角色加入AuthorizationInfo认证对象
        info.setRoles(roles);
        // 权限加入AuthorizationInfo认证对象
        info.setStringPermissions(menus);
        return info;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("ShiroRealm.doGetAuthenticationInfo()");
        //这里的upToken就是用户自己输入的账号密码，这里是token，在后续shiro会用assertCrenditialMatch方法进行doGetAuthenticationInfo返回的
        //info进行比对，也就是说token是用户输入的信息，info是对应数据库里面正确的账号密码信息，后续再比对
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        User user = null;
        try
        {
            user = l.selectUserByUserName(username);
        }
        catch (Exception e)
        {
            log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getName(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
        return info;
//
//        //获取用户的输入的账号.
//        String username = (String)token.getPrincipal();
//        //通过username从数据库中查找 User对象，如果找到，没找到.
//        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
////        User userInfo = userInfoService.findByUsername(username);
////        if(userInfo == null){
////            return null;
////        }
//        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
////                userInfo, //用户名
////                userInfo.getPassword(), //密码
////                ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt
////                getName()  //realm name
//        );
//        return authenticationInfo;
    }

}